package com.gmlive.gradle.versionlint.repositories

import com.gmlive.gradle.versionlint.cache.LibraryCache
import com.gmlive.gradle.versionlint.library.Library
import com.gmlive.gradle.versionlint.library.isGoogleLib
import com.gmlive.gradle.versionlint.library.isInkeLib
import com.gmlive.gradle.versionlint.library.isJitpackLib
import com.gmlive.gradle.versionlint.repositories.RepositoryResult.ArtifactNotFound
import com.gmlive.gradle.versionlint.repositories.RepositoryResult.NewVersionAvailable
import okhttp3.OkHttpClient

@Suppress("UnstableApiUsage")
internal class MavenRemoteRepositoryHandler(
    private val client: OkHttpClient,
    private val cache: LibraryCache
) {

    private val google by lazy { GoogleMaven(client) }
    private val inke by lazy { InkeRepository(client) }
    private val mavenCentral by lazy { MavenCentral(client) }
    private val jcenter by lazy { JCenter(client) }
    private val jitpack by lazy { Jitpack(client) }

    fun getNewVersionAvailable(
        library: Library,
        resultListener: (result: RepositoryResult) -> Unit
    ) {
        val cachedLibrary = cache.get(library.groupId, library.artifactId)
        if (cachedLibrary != null && cachedLibrary != library) {
            resultListener.invoke(NewVersionAvailable(cachedLibrary))
            return
        }
        when {
            library.isInkeLib() ->{
                inke.findNewVersionFromLibrary(library) {
                    if (it is NewVersionAvailable) cache.add(it.version)
                    resultListener.invoke(it)
                }
            }
            library.isGoogleLib() -> {
                google.findNewVersionFromLibrary(library) {
                    if (it is NewVersionAvailable) cache.add(it.version)
                    resultListener.invoke(it)
                }
            }
            library.isJitpackLib() -> {
                jitpack.findNewVersionFromLibrary(library) {
                    if (it is NewVersionAvailable) cache.add(it.version)
                    resultListener.invoke(it)
                }
            }
            else -> {
                mavenCentral.findNewVersionFromLibrary(library) {
                    if (it is NewVersionAvailable) cache.add(it.version)
                    if (it is ArtifactNotFound) {
                        jcenter.findNewVersionFromLibrary(library) { result ->
                            if (result is NewVersionAvailable) cache.add(result.version)
                            resultListener.invoke(result)
                        }
                    } else {
                        resultListener.invoke(it)
                    }
                }
            }
        }
    }

}
